<script setup>
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { getOrderList, cancelOrder, payOrder, payArrears, confirmOrder, delOrder, getOrder } from '@/api/shop'
	import { parseTime } from '@/utils/common'
	
	const buttonStyle = ref({width: '160rpx'})
	const loading = ref(false)
	const loadStatus = ref('loadmore')
	const navList = [{name: '全部'}, {name: '待付款'}, {name: '待提货'}, {name: '退款/售后'}]
	const query = ref({status: 0, current: 1, size: 20})
	const triggered = ref(false)
	const total = ref(0)
	const list = ref([])
	const operateId = ref(null)
	const refreshId = ref(null)
	const codeArr = ref([])
	const timeData = ref({})
	
	const cancelModal = ref(null)
	const urgeModal = ref(null)
	const confirmModal = ref(null)
	const delModal = ref(null)
	const pickUpPopup = ref(null)
	
	function navChange(e) {
		let index = e.index
		if(query.value.status !== index) {
			query.value.status = index
			triggered.value = true
		}
	}
	function goView(item) {
		if(item.type === 'ACTIVITY') return
		let url = '/pages/shop/orderDetail?id=' + item.orderId
		if(item.saleStatus) url = '/pages/shop/orderSalesDetail?id=' + item.orderId
		uni.navigateTo({
			url,
			success: () => {
				refreshId.value = item.orderId
			}
		})
	}
	function contact() {
		uni.makePhoneCall({
			phoneNumber: '18200000000'
		})
	}
	function refreshList() {
		if(loadStatus.value === 'loading') return
		loadStatus.value = 'loading'
		triggered.value = true
		list.value = []
		query.value.current = 1
		let params = dealQuery()
		getOrderList(params).then(res => {
			let result = res.result || {}
			let data = result.records || []
			total.value = Number(result.total)
			data.forEach(item => {
				if(item.status === 1 && item.type !== 'INTEGRAL') {
					item.countdown = computeCountTime(parseTime(item.createTime, '{y}/{m}/{d} {h}:{i}:{s}'))
				}
			})
			list.value = data
			triggered.value = false
			let curLength = list.value.length || 0
			loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
		}).catch(() => {
			triggered.value = false
			loadStatus.value = 'loadmore'
		})
	}
	function lowerList(noReplace = true) {
		if(list.value.length < total.value || !noReplace){
			loadStatus.value = 'loading'
			query.value.current ++
			let params = dealQuery()
			getOrderList(params).then(res => {
				let result = res.result || {}
				let data = result.records || []
				total.value = Number(result.total)
				data.forEach(item => {
					if(item.status === 1 && item.type !== 'INTEGRAL') {
						item.countdown = computeCountTime(parseTime(item.createTime, '{y}/{m}/{d} {h}:{i}:{s}'))
					}
				})
				if(noReplace) {
					list.value.push(...data)
				} else {
					const preList = list.value.slice(0, (query.value.current - 1) * query.value.size)
					list.value = preList.concat(data)
				}
				let curLength = list.value.length || 0
				loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
			}).catch(() => {
				query.value.current --
				loadStatus.value = 'loadmore'
			})
		}
	}
	function restore() {
		triggered.value = false
	}
	function refreshItem(id) {
		let index = list.value.findIndex(item => item.orderId === id)
		if(index != -1) {
			query.value.current = Math.floor(index / query.value.size)
			lowerList(false)
		}
	}
	function dealQuery() {
		let params = {}
		for (let name in query.value) {
			const value = query.value[name]
			if(value != undefined) params[name] = value
		}
		let orderStatus = statusToOrder(query.value.status)
		params.orderArray = orderStatus.orderArray
		params.saleArray = orderStatus.saleArray
		if(!params.orderArray) delete params.orderArray
		if(!params.saleArray) delete params.saleArray
		delete params.status
		return params
	}
	function computeCountTime(timeStr) {
		let nowTimeStamp = +new Date()
		let endTimeStamp = +new Date(timeStr) + 15 * 60 * 1000
		let seconds = endTimeStamp - nowTimeStamp
		return seconds > 0? seconds : 0
	}
	function countFinish(item) {
		item.countdown = 0
		item.status = 0
	}
	function statusToOrder(value) {
		let data = {orderArray: '', saleArray: ''}
		switch(value) {
			case 0: 
				break;
			case 1:
				data.orderArray = '1,8'
				break;
			case 2:
				data.orderArray = "2,3,4,5,6,7"
				break;
			case 3:
				data.saleArray = "1,2,3"
				break;
			default: 
				break;
		}
		return data;
	}
	function statusToText(value) {
		switch(value) {
			case 0: return '已关闭';
			case 1: return '待付押金';
			case 2: return '已付押金';
			case 3: return '待分拣';
			case 4: return '待出库';
			case 5: return '待发货';
			case 6: return '待收货';
			case 7: return '待确认';
			case 8: return '待付尾款';
			case 9: return '已完成';
			default: return '未知'
		}
	}
	function salesToText(value) {
		switch(value) {
			case 1: return '售后中';
			case 2: return '售后通过';
			case 3: return '售后驳回';
			default: return '未知'
		}
	}
	function typeToText(value) {
		switch(value) {
			case 'CLOSED': return '包装破损';
			case 'ORDERED': return '商品质量问题';
			case 'PAID': return '发错货';
			case 'SHIPPED': return '商品与描述不符';
			case 'DELIVERED': return '其他';
			default: return '未知'
		}
	}
	function cancel(id) {
		operateId.value = id
		cancelModal.value.open()
	}
	function confirmCancel() {
		loading.value = true
		cancelOrder(operateId.value).then(res => {
			loading.value = false
			uni.showToast({icon: 'success', title: '取消成功'})
			setTimeout(() => {
				refreshItem(operateId.value)
				closeCancel()
			})
		}).catch(() => loading.value = false)
	}
	function closeCancel() {
		operateId.value = undefined
	}
	function pay(id, successStatus = 1) {
		loading.value = true
		payOrder(id).then(res => {
			loading.value = false
			let data = res.result
			getOrder(id, false).then(res => {
				let result = res.result || {list: []}
				let info = {
					status: successStatus,
					addrName: result.logisticsType === 2? result.receiverDetailAddress : '茗山总仓（某某小学附近）',
					addr: result.logisticsType === 2? result.receiverAddress : '四川省雅安市茗山区前进镇桥楼村99号',
					expectedTime: result.expectedTime,
					logisticsType: result.logisticsType
				}
				if(data) {
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.packageVal,
						signType: data.signType,
						paySign: data.paySign,
						success: (data) => {
							if(result.type === 'ACTIVITY') {
								uni.showToast({icon: 'none', title: '支付成功'})
								refreshItem(id)
							}else {
								info.status = successStatus + 1
								let params = JSON.stringify(info)
								uni.redirectTo({
									url: '/pages/shop/orderPay?params='+ params,
								})
							}
						},
						fail: (err) => {
							if(result.type === 'ACTIVITY') {
								uni.showToast({icon: 'none', title: '支付失败'})
							}else {
								let params = JSON.stringify(info)
								uni.redirectTo({
									url: '/pages/shop/orderPay?params='+ params,
								})
							}
						}
					})
				} else {
					let params = JSON.stringify(info)
					uni.redirectTo({
						url: '/pages/shop/orderPay?params='+ params,
					})
					user.getInfoAction()
				}
			})
		}).catch(() => loading.value = false)
	}
	function sales(id) {
		uni.navigateTo({
			url: '/pages/shop/orderSales?id=' + id,
			success: () => {
				refreshId.value = id
			}
		})
	}
	function urge(id) {
		operateId.value = id
		urgeModal.value.open()
	}
	function confirmUrge() {
		uni.showToast({icon: 'success', title: '催促成功'})
		closeUrge()
	}
	function closeUrge() {
		operateId.value = undefined
	}
	function confirm(id) {
		operateId.value = id
		confirmModal.value.open()
	}
	function confirmConfirm() {
		loading.value = true
		confirmOrder(operateId.value).then(res => {
			loading.value = false
			uni.showToast({icon: 'success', title: '确认成功'})
			setTimeout(() => {
				refreshItem(operateId.value)
				closeConfirm()
			}, 200)
		}).catch(() => loading.value = false)
	}
	function closeConfirm() {
		operateId.value = undefined
	}
	function pickUp(deliveryCode) {
		operateId.value = deliveryCode
		codeArr.value = deliveryCode.split('')
		pickUpPopup.value.open()
	}
	function confirmPickUp() {
		closePickUp()
	}
	function closePickUp() {
		operateId.value = undefined
		codeArr.value = []
		pickUpPopup.value.close()
	}
	function del(id) {
		operateId.value = id
		delModal.value.open()
	}
	function confirmDel() {
		loading.value = true
		delOrder(operateId.value).then(res => {
			loading.value = false
			uni.showToast({icon: 'success', title: '删除成功'})
			setTimeout(() => {
				refreshItem(operateId.value)
				closeDel()
			}, 200)
		}).catch(() => loading.value = false)
	}
	function closeDel() {
		operateId.value = undefined
	}
	function again(id) {
		
	}
	
	onLoad((option) => {
		let index = Number(option.status || 0)
		query.value.status = index < 3?  index + 1 : 0
	})
	onShow(() => {
		if(refreshId.value) {
			refreshItem(refreshId.value)
			refreshId.value = undefined
		} else {
			triggered.value = true
		}
	})
</script>

<template>
	<view class="app-container">
		<view class="app-head">
			<uv-tabs :list="navList" :current="query.status" :activeStyle="{color: '#1A1816', fontWeight: 'bold'}" :inactiveStyle="{color: '#606060'}"  @change="navChange" lineWidth="60" :lineHeight="6" lineColor="#FF3E49" :scrollable="false" :disabled="loadStatus === 'loading'"></uv-tabs>
		</view>
		<scroll-view scroll-y="true" class="app-content" refresher-enabled :refresher-triggered="triggered" @refresherrefresh="refreshList" lower-threshold="10" @scrolltolower="lowerList" @refresherrestore="restore">
			<view class="content-list" v-if="list.length">
				<view class="list-box" v-for="item in list" :key="item.orderId" @click="goView(item)">
					<view class="head">
						<view class="head-left">{{item.createTime}}</view>
						<view class="head-right">
							<view class="count-down" v-if="item.countdown">
								<text>剩余付款时间</text>
								<uv-count-down :time="item.countdown" format="mm:ss" @finish="countFinish(item)"></uv-count-down>
							</view>
							<view v-else-if="item.saleStatus" class="tag" :class="'sale-' + item.saleStatus">{{salesToText(item.saleStatus)}}</view>
							<view v-else class="tag" :class="'tag-' + item.status">{{statusToText(item.status)}}</view>
						</view>
					</view>
					<template v-if="item.type === 'ACTIVITY'">
						<view class="activity" v-if="item.list">{{item.list[0]?.name}}</view>
					</template>
					<template v-else>
						<view class="list" v-if="item.list">
							<uv-image v-for="goods in item.list" :key="goods.goodsId" :src="goods.image && goods.image.furl" width="128" height="128"></uv-image>
							<view class="list-more"><text>共{{item.list.length || 0}}件</text><uv-icon name="arrow-right" color="#000000" size="24" /></view>
						</view>
					</template>
					<view class="total">
						<text>实付款</text>
						<text class="total-points" v-if="item.type === 'INTEGRAL'">{{item.payAmount || 0}}</text>
						<text class="total-price" v-else>{{item.payAmount ? item.payAmount.toFixed(2) : 0.00}}</text>
					</view>
					<view class="sales" v-if="item.saleStatus">
						<view class="sales-des uv-line-1"><text>退款/售后原因：</text><text class="sales-des-value">{{typeToText(item.reason)}}</text></view>
						<view class="sales-bottom theme-btn" @click.stop>
							<view>申请时间：{{item.applyTime || '--'}}</view>
							<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="联系平台" @click="contact" :disabled="loading"
								:plain="true"></uv-button>
						</view>
					</view>
					<view class="bottom theme-btn" @click.stop v-else >
						<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="取消订单" @click="cancel(item.orderId)" 
							:disabled="loading" :plain="true" v-if="item.status === 1"></uv-button>
						<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="付押金" @click="pay(item.orderId, 1)"
							:disabled="loading" v-if="item.status === 1"></uv-button>
						<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="申请售后" @click="sales(item.orderId)" 
							:disabled="loading" :plain="true" v-if="[2,3,4,5,6,7].includes(item.status) || item.saleStatus === 3"></uv-button>
						<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="付尾款" @click="pay(item.orderId, 3)"
							:disabled="loading" v-if="item.status === 8"></uv-button>
						<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="催促发货" @click="urge(item.orderId)"
							:disabled="loading" :plain="true" v-if="[2,3,4,5].includes(item.status)"></uv-button>
						<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="取货码" @click="pickUp(item.deliveryCode)"
							:disabled="loading" v-if="item.status === 6"></uv-button>
						<uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="确认收货" @click="confirm(item.orderId)"
							:disabled="loading" v-if="item.status === 7"></uv-button>
						<uv-button color="#606060" shape="circle" size="small" :custom-style="buttonStyle" text="删除订单" @click="del(item.orderId)"
							:disabled="loading" :plain="true" v-if="item.status === 9 || item.status === 0"></uv-button>
						<!-- <uv-button color="#FF3E49" shape="circle" size="small" :custom-style="buttonStyle" text="再次购买" @click="again(item.orderId)"
							:disabled="loading" v-if="item.status === 5"></uv-button> -->
					</view>
				</view>
				<uv-load-more :status="loadStatus" fontSize="28" iconSize="34"></uv-load-more>
			</view>
			<empty text="没有找到您的订单" v-else></empty>
		</scroll-view>
		
		<uv-modal ref="cancelModal" @confirm="confirmCancel" @cancel="closeCancel" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定取消订单吗?</view>
		</uv-modal>
		<uv-modal ref="urgeModal" @confirm="confirmUrge" @cancel="closeUrge" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定催促发货吗?</view>
		</uv-modal>
		<uv-modal ref="confirmModal" @confirm="confirmUrge" @cancel="closeUrge" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定收货吗?</view>
		</uv-modal>
		<uv-modal ref="delModal" @confirm="confirmDel" @cancel="closeDel" confirmColor="#FF3E49" showCancelButton>
			<view class="modal-content">确定删除订单吗?</view>
		</uv-modal>
		
		<uv-popup ref="pickUpPopup" closeable mode="center" bgColor="none">
			<view class="popup-box">
				<view class="popup-title">取货码</view>
				<view class="popup-content">
					<view class="code-box">
						<view class="code-item">{{codeArr[0] || '-'}}</view>
						<view class="code-item">{{codeArr[1] || '-'}}</view>
						<view class="code-item">{{codeArr[2] || '-'}}</view>
						<view class="code-item">{{codeArr[3] || '-'}}</view>
					</view>
				</view>
				<view class="popup-bottom">
					<uv-button shape="circle" :custom-style="{width: '295rpx', background: '#ffffff', border: '2rpx solid #FF1313', color: '#FF1313'}"
						text="取消" @click="closePickUp"></uv-button>
					<uv-button color="linear-gradient(102deg, #FA3F00 0%, #FF7445 100%)" shape="circle" :custom-style="{width: '295rpx'}" text="确定"
						@click="confirmPickUp"></uv-button>
				</view>
			</view>
		</uv-popup>
		
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		height: 100vh;
		padding-top: 2rpx;
		.app-head{
			background-color: #FFFFFF;
		}
		.app-content{
			width: 100%;
			height: calc(100% - 88rpx);
			.content-list{
				padding: 16rpx 0;
				display: flex;
				flex-direction: column;
				gap: 16rpx;
			}
		}
		.list-box{
			padding: 24rpx 32rpx;
			background-color: #FFFFFF;
			.head{
				display: flex;
				justify-content: space-between;
				align-items: center;
				gap: 16rpx;
				color: #606060;
				.head-left{
					flex: 1;
				}
				.head-right{
					flex-shrink: 0;
					.count-down{
						display: flex;
						align-items: center;
						gap: 8rpx;
						::v-deep .uv-count-down__text{
							font-weight: 600;
							font-size: var(--theme-lg);
							line-height: var(--theme-lg-line);
							color: #FD1024;
						}
					}
					.tag{
						background-color: #F7F8FA;
						color: #7c8088;
						padding: 4rpx 12rpx;
						border-radius: 4rpx;
						&.tag-2, &.tag-3,&.tag-4,&.tag-5,&.tag-6,&.tag-8, &.sale-3{
							background-color: rgba(255,118,64,0.1);
							color: #FF7640;
						}
						&.tag-7, &.tag-9, &.sale-2{
							background-color: rgba(16,176,45,0.1);
							color: #10B02D;
						}
					}
				}
			}
			.list{
				margin-top: 28rpx;
				display: flex;
				gap: 16rpx;
				position: relative;
				overflow: hidden;
				.list-more{
					position: absolute;
					top: 0;
					right: 0;
					bottom: 0;
					z-index: 10;
					width: 104rpx;
					display: flex;
					justify-content: flex-end;
					align-items: center;
					background-image: url('https://erp-1307466921.cos.ap-shanghai.myqcloud.com/2025/07/1948649435561930752.png');
					font-size: var(--theme-sm);
					line-height: var(--theme-sm-line);
				}
			}
			.activity{
				margin-top: 16rpx;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
			}
			.total{
				margin-top: 16rpx;
				display: flex;
				justify-content: flex-end;
				gap: 8rpx;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
				.total-points{
					font-size: 40rpx;
					font-weight: 600;
					color: #FF0D0D;
					&::after{
						content: "积分";
						font-size: 60%;
					}
				}
				.total-price {
					font-size: 40rpx;
					font-weight: 600;
					color: #FF0D0D;
					&::before{
						content: "¥";
						font-size: 60%;
					}
				}
			}
			.sales{
				margin-top: 16rpx;
				color: #606060;
				.sales-des{
					padding-bottom: 16rpx;
					border-bottom: 2rpx solid #F4F4F4;
				}
				.sales-des-value{
					color: #000000;
				}
				.sales-bottom{
					margin-top: 16rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					gap: 12rpx;
				}
			}
			.bottom{
				margin-top: 32rpx;
				display: flex;
				justify-content: flex-end;
				gap: 12rpx;
			}
		}
		.modal-content{
			text-align: center;
			font-weight: 600;
			color: #000000;
			font-size: var(--theme-lg);
			line-height: var(--theme-lg-line);
		}
		.popup-box{
			width: 686rpx;
			background: linear-gradient( 180deg, #F9E7E7 0%, #FFFFFF 24%);
			border-radius: 32rpx;
			padding: 32rpx;
			.popup-title{
				padding-bottom: 24rpx;
				font-weight: 600;
				font-size: var(--theme-lg);
				line-height: var(--theme-lg-line);
			}
			.popup-content{
				.code-box{
					margin-top: 14rpx;
					display: flex;
					justify-content: center;
					gap: 48rpx;
					font-size: 56rpx;
					color: #202020;
					.code-item{
						width: 112rpx;
						height: 112rpx;
						text-align: center;
						line-height: 112rpx;
						background-color: rgba(32,32,32,0.04);
						border-radius: 20rpx;
					}
				}
			}
			.popup-bottom{
				padding-top: 32rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 32rpx;
			}
		}
	}
</style>